package cn.com.dreamtouch.magicbox_common.model;

import java.io.IOException;

import cn.com.dreamtouch.common.DTLog;
import retrofit2.adapter.rxjava.HttpException;

/**
 * Created by MuHan on 17/2/21.
 */

public class MagicBoxResponseException  extends Exception {
    String resultCode;
    MsgModel resultMessage;

    public MagicBoxResponseException(String resultCode, MsgModel resultMessage) {
        this.resultCode = resultCode;
        this.resultMessage = resultMessage;
        this.initCause(new Throwable(resultMessage.error));
    }

    public String getResultCode() {
        return this.resultCode;
    }

    public MsgModel getResultMessage() {
        return this.resultMessage;
    }

    public static MagicBoxResponseException convertApiThrowable(Throwable throwable) {
        DTLog.e("convertApiThrowable", throwable.getMessage());
        throwable.printStackTrace();
        MagicBoxResponseException apiException;
        if(throwable instanceof MagicBoxResponseException) {
            apiException = (MagicBoxResponseException)throwable;
        } else {
            MsgModel result;
            if(throwable instanceof HttpException) {
                result = new MsgModel();
                result.error = throwable.getMessage();
                if(((HttpException)throwable).code()==401)
                {
                    result.prompt = "身份验证过期，请重新登录";
                    apiException = new MagicBoxResponseException("Unauthorized", result);
                }
                else
                    {
                    result.prompt = "服务器连接失败";
                    apiException = new MagicBoxResponseException("ConnectFail", result);
                }
            } else if(throwable instanceof IOException) {
                result = new MsgModel();
                result.error = throwable.getMessage();
                result.prompt = "网络超时，请重试";
                apiException = new MagicBoxResponseException("Timeout", result);
            } else {
                result = new MsgModel();
                result.error = throwable.getMessage();
                result.prompt = "未知错误,请重试";
                apiException = new MagicBoxResponseException("UnknownError", result);
            }
        }

        return apiException;
    }
    public static class MsgModel {
        public String prompt;
        public String error;
        public Object extData;
        public MsgModel() {
        }
    }

}
